﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Windows.Forms;
using KingTools.CacheHelper;
using KingTools.CommonsHelper.Constants;
using KingTools.CommonsHelper.Model;
using KingTools.SocketHelper;
using KingTools.SocketHelper.Model;
using KingTools.XmlHelper;

namespace KingTools
{
    public partial class frmMain : Form
    {
        private BeginAceptHandler initSocket;
        private AsySocketUtils socketUtils;

        public frmMain()
        {
            InitializeComponent();

            var xml = new XmlUtils();
            xml.FilePath = Constants.XML_PATH;
            xml.OpenXML();
            List<Item> Items = xml.GetXmlNodesByItemChildNodes(Constants.XML_CLEAN_URLS_PATH);
            cboCacheUrls.Items.Clear();
            cboCacheUrls.DataSource = Items;
            cboCacheUrls.DisplayMember = "name";
            cboCacheUrls.ValueMember = "value";
            cboCacheUrls.SelectedIndex = 0;

            Items = xml.GetXmlNodesByItemChildNodes(Constants.XML_CACHES_PATH);

            cboCacheType.Items.Clear();
            cboCacheType.DataSource = Items;
            cboCacheType.DisplayMember = "name";
            cboCacheType.ValueMember = "value";
            cboCacheType.SelectedIndex = 0;
            Text = Text + " - V" + Assembly.GetExecutingAssembly().GetName().Version;
        }

        /// <summary>
        ///     初始化 Socket 链接
        /// </summary>
        private void init()
        {
            if (cboProServer.Text.Trim().Length <= 0 || cboProPort.Text.Trim().Length <= 0)
            {
                AppendText("服务器与端口号为空！");
                return;
            }

            if (socketUtils == null)
            {
                socketUtils = new AsySocketUtils(cboProServer.Text.Trim(), cboProPort.Text.Trim(), AppendText);
            }

            if (initSocket == null)
            {
                initSocket = socketUtils.BeginAccept;
            }
        }

        public void AppendText(string Message)
        {
            if (txtResult.InvokeRequired)
            {
                MessageHandler msgHandler = AppendText;
                Invoke(msgHandler, new Object[] {Message + "\n"});
            }
            else
            {
                txtResult.AppendText(Message + "\n");
            }
        }

        private void btnCache_Click(object sender, EventArgs e)
        {
            if (txtKeyRule.TextLength <= 0 && txtPlayerId.TextLength <= 0)
            {
                MessageBox.Show("相关信息不完整！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string url = "";

            if (txtKeyRule.TextLength <= 0 && txtPlayerId.TextLength > 0)
            {
                url = String.Format(((Item) cboCacheUrls.SelectedItem).value, ((Item) cboCacheType.SelectedItem).value,
                                    txtPlayerId.Text);
            }
            else
            {
                url = String.Format(((Item) cboCacheUrls.SelectedItem).value, ((Item) cboCacheType.SelectedItem).value,
                                    txtKeyRule.Text + "_" + txtPlayerId.Text);
            }

            if (DialogResult.Yes ==
                MessageBox.Show("您确定要清除缓存吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                if (CacheUtils.UrlToExecute(url, txtResult))
                {
                    MessageBox.Show("缓存清理成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("缓存清理失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnLocal_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes ==
                MessageBox.Show("您确定要停止本地服务器吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                if (CacheUtils.UrlToExecute(Constants.LOCAL_STOP_SERVER_URL, txtResult))
                {
                    MessageBox.Show("本地服务器停止成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("本地服务器停止失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnRemote_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes ==
                MessageBox.Show("您确定要停止测试服务器吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                if (CacheUtils.UrlToExecute(Constants.REMOTE_SERVER_STOP_URL, txtResult))
                {
                    MessageBox.Show("测试服务器停止成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("测试服务器停止失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnRequest_Click(object sender, EventArgs e)
        {
            init();

            if (txtProtocol.Text.Trim().Length <= 0)
            {
                AppendText("协议不能为空！");
                return;
            }

            if (txtPlayerName.Text.Trim().Length <= 0)
            {
                AppendText("用户不能为空！");
                return;
            }

            if (!txtPlayerName.Text.Trim().Equals(Constants.USER_NAME))
            {
                Constants.USER_NAME = txtPlayerName.Text.Trim();
                Constants.isConnect = true;
                Constants.isLogin = true;
                Constants.isVerify = true;
                Constants.RECONNECTION = true;
            }

            var baseVo = new ProtocolBaseVO();
            var loginVo = new ProtocolLoginVO();
            var businessVo = new ProtocolBusinessVO();

            baseVo.protocolId = 1001;

            loginVo.baseVO = baseVo;
            loginVo.gsession = txtPlayerName.Text;
            loginVo.openId = Constants.USER_NAME;
            loginVo.openKey = "1";
            loginVo.pf = "qqgame";
            loginVo.pfKey = "1";
            loginVo.oprId = 3002;
            loginVo.first = 1;
            loginVo.xy = "";
            loginVo.recommend = 0;
            loginVo.nickname = "";

            baseVo = new ProtocolBaseVO();
            baseVo.protocolId = short.Parse(txtProtocol.Text);
            businessVo.baseVO = baseVo;
            businessVo.data = getData();

            var send = new SendUtils(loginVo, businessVo);

            initSocket.BeginInvoke(send, null, null);
        }

        /// <summary>
        ///     获取 ListView 数据 To HashTable
        /// </summary>
        /// <returns>Hashtable</returns>
        private ArrayList getData()
        {
            var list = new ArrayList();
            if (lvwSendType.Items.Count > 0)
            {
                foreach (ListViewItem lvi in lvwSendType.Items)
                {
                    var item = new Item(lvi.Text, lvi.SubItems[1].Text);
                    list.Add(item);
                }
            }

            return list;
        }

        private void btnSendAdd_Click(object sender, EventArgs e)
        {
            if (cboSendType.Text.Length > 0 && txtSendValue.Text.Trim().Length > 0)
            {
                //int index = lvwSendType.Items.Count;
                string type = cboSendType.Text;
                string value = txtSendValue.Text;
                var lvi = new ListViewItem();
                lvi.SubItems[0].Text = type;
                lvi.SubItems.Add(value);
                lvwSendType.Items.Add(lvi);
                // lvwSendType.Items[index].Selected = true;
                // lvwSendType.Focus();
                txtSendValue.SelectAll();
                txtSendValue.Focus();
            }
        }

        private void btnReduce_Click(object sender, EventArgs e)
        {
            if (lvwSendType.SelectedItems.Count > 0)
            {
                int index = lvwSendType.SelectedItems[0].Index;
                int count = lvwSendType.Items.Count;
                lvwSendType.Items.RemoveAt(lvwSendType.SelectedItems[0].Index);

                if (count != 1)
                {
                    if (index == count - 1)
                    {
                        index = lvwSendType.Items.Count - 1;
                    }

                    lvwSendType.Items[index].Selected = true;
                }

                lvwSendType.Focus();
            }
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            if (lvwSendType.SelectedItems.Count > 0)
            {
                int index = lvwSendType.SelectedItems[0].Index - 1;

                if (index == -1)
                {
                    index = lvwSendType.Items.Count - 1;
                }

                string text = lvwSendType.SelectedItems[0].Text;
                string subText = lvwSendType.SelectedItems[0].SubItems[1].Text;
                var lviIndex = new ListViewItem(new[] {text, subText});

                ListViewItem lviUpIndex = lvwSendType.Items[index];

                lvwSendType.SelectedItems[0].Text = lviUpIndex.Text;
                lvwSendType.SelectedItems[0].SubItems[1].Text = lviUpIndex.SubItems[1].Text;

                lvwSendType.Items[index] = lviIndex;

                lvwSendType.Items[index].Selected = true;
                if (index == lvwSendType.Items.Count - 1)
                {
                    lvwSendType.Items[0].Selected = false;
                }
                else
                {
                    lvwSendType.Items[index + 1].Selected = false;
                }
                lvwSendType.Focus();

                //lvwSendType.Refresh();
            }
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            if (lvwSendType.SelectedItems.Count > 0)
            {
                int index = lvwSendType.SelectedItems[0].Index + 1;

                if (index == lvwSendType.Items.Count)
                {
                    index = 0;
                }

                string text = lvwSendType.SelectedItems[0].Text;
                string subText = lvwSendType.SelectedItems[0].SubItems[1].Text;
                var lviIndex = new ListViewItem(new[] {text, subText});
                ListViewItem lviDownIndex = lvwSendType.Items[index];

                lvwSendType.SelectedItems[0].Text = lviDownIndex.Text;
                lvwSendType.SelectedItems[0].SubItems[1].Text = lviDownIndex.SubItems[1].Text;

                lvwSendType.Items[index] = lviIndex;

                lvwSendType.Items[index].Selected = true;

                if (index == 0)
                {
                    lvwSendType.Items[lvwSendType.Items.Count - 1].Selected = false;
                }
                else
                {
                    lvwSendType.Items[index - 1].Selected = false;
                }

                lvwSendType.Focus();

                //lvwSendType.Refresh();
            }
        }

        private void btnCleanAllLocal_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes ==
                MessageBox.Show("您确定要清除本地服务器全部缓存吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                if (CacheUtils.UrlToExecute(Constants.LOCAL_CLEAN_CACHE_URL, txtResult))
                {
                    MessageBox.Show("本地服务器缓存全部清除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("本地服务器缓存全部清除失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnCleanAllRemote_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes ==
                MessageBox.Show("您确定要清除远程服务器全部缓存吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                if (CacheUtils.UrlToExecute(Constants.REMOTE_CLEAN_CACHE_URL, txtResult))
                {
                    MessageBox.Show("远程服务器缓存全部清除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("远程服务器缓存全部清除失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnReloadDict_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes ==
                MessageBox.Show("您确定要重新加载基础数据缓存吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                if (CacheUtils.UrlToExecute(Constants.RELOAD_DICT_CACHE_URL, txtResult))
                {
                    MessageBox.Show("重新加载基础数据缓存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("重新加载基础数据缓存失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnSyncPloy_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes ==
                MessageBox.Show("您确定要同步测试服活动到14吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                if (CacheUtils.UrlToExecute(Constants.SYNC_INTERNET_TEST_PLOY_URL, txtResult))
                {
                    MessageBox.Show("同步测试服活动成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("同步测试服活动失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnRemoteReloadDict_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes ==
                MessageBox.Show("您确定要重新加载基础数据缓存吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                if (CacheUtils.UrlToExecute(Constants.REMOTE_RELOAD_DICT_CACHE_URL, txtResult))
                {
                    MessageBox.Show("重新加载基础数据缓存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("重新加载基础数据缓存失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void lvwSendType_Click(object sender, EventArgs e)
        {
            if (lvwSendType.SelectedItems[0].Selected)
            {
                ListViewItem lvi = lvwSendType.SelectedItems[0];
                var paramValue = new frmParamValue(lvi);
                paramValue.ShowDialog();
            }
        }
    }
}